<template>
  <div class="search">
    <div class="header">
      <span class="iconfont iconjiantou2" @click="$router.back()"></span>
      <van-search placeholder="请输入搜索关键词" shape="round" v-model="search">
      </van-search>
      <div @click="onSearch">搜索</div>
    </div>
    <div class="historyList">
      <h2>历史记录</h2>
      <div v-for="item in searchKey" :key="item" @click="searchHistory(item)">
        {{ item }}
      </div>
    </div>
    <div class="resultList">
      <h2>搜索结果</h2>
      <router-link
        :to="/articleDetail/ + item.id"
        v-for="item in resault"
        :key="item.id"
        >{{ item.title }}</router-link
      >
    </div>
  </div>
</template>

<script>
import { searchArticle } from "@/api/post";
export default {
  data() {
    return {
      search: "",
      resault: [],
      searchKey: [],
    };
  },
  methods: {
    async onSearch() {
      if (this.search.trim().length == 0) {
        this.$toast.fail("请输入关键字");
        return;
      }
      let res = await searchArticle({ keyword: this.search });
      console.log(res);
      this.resault = res.data.data;

      /* this.searchKey = JSON.parse(localStorage.getItem("searchKey")) || []; */

      //判断是否有搜索过该关键字
      let index = this.searchKey.indexOf(this.search);
      if (index != -1) {
        this.searchKey.splice(index, 1);
      }
      //给数组添加历史数据
      this.searchKey.unshift(this.search);
      //搜索关键字 保存到本地
      localStorage.setItem("searchKey", JSON.stringify(this.searchKey));
    },
    searchHistory(item) {
      this.search = item;
      this.onSearch();
    },
  },
  mounted() {
    //页面一加载 要读取历史记录 如果没有数据 就先存入一个空数组
    this.searchKey = JSON.parse(localStorage.getItem("searchKey")) || [];
    //console.log(this.searchKey);
  },
};
</script>

<style lang="less" scoped>
.header {
  display: flex;
  height: 50px;
  justify-content: space-between;
  align-items: center;
  padding: 0 10px;
  border-bottom: 1px solid #ccc;
  .van-search {
    flex: 1;
    padding: 5px 12px;
  }
}
.historyList,
.resultList {
  padding: 10px;
  border-bottom: 1px solid #ccc;
  .historyItem {
    line-height: 26px;
    border-bottom: 1px dashed #ccc;
  }
  h2 {
    line-height: 40px;
    font-weight: bold;
  }
  > a {
    display: block;
    text-decoration: underline;
    line-height: 30px;
    color: rgb(113, 112, 112);
  }
}
</style>